package com.lee9213.thread;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author libo
 * @version 1.0
 * @date 2017/7/27 15:25
 */
public class BankWaterService {

    private CyclicBarrier barrier = new CyclicBarrier(4, new A());
    private Executor executor = Executors.newFixedThreadPool(4);
    private static ConcurrentHashMap<String, Integer> bankWaterCount = new ConcurrentHashMap<>();

    private void count() {
        System.out.println(1);
        for (int i = 0; i < 4; i++) {
            System.out.println(2);
            executor.execute(() -> {
                bankWaterCount.put(Thread.currentThread().getName(), 1);
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(5);
            });
        }
    }

    static class A implements Runnable {

        @Override
        public void run() {
            System.out.println(3);
            int result = 0;
            for (Map.Entry<String, Integer> entry : bankWaterCount.entrySet()) {
                result += entry.getValue();
            }

            bankWaterCount.put("result", result);
            System.out.println(result);
        }

    }

    public static void main(String[] args) {
        BankWaterService bankWaterService = new BankWaterService();
        bankWaterService.count();
    }
}
